Using the ::selection Pseudo-Element in CSS
The ::selection pseudo-element in CSS allows you to style the portion of text that a user highlights (selects) with their cursor. It provides a way to customize the appearance of selected text, such as changing its background color, text color, or adding other visual effects.
::selection applies only to the text a user selects.
You can style properties like color, background-color, text-shadow, and cursor.
Not all CSS properties are supported; mainly visual text properties work.
It works on most elements that contain selectable text.
In this example, when the user selects the paragraph text, the background changes to blue, the text color becomes white, and a subtle text shadow is applied, enhancing the visual feedback of text selection.
Use ::selection to improve user experience and match your site's color scheme.
Keep contrast high for readability when styling selections.
Test across different browsers, as some older browsers may have limited support.
Avoid adding complex animations or non-text styles, as these are not supported.
How would you change the background color of selected text to yellow in a paragraph, and what CSS properties would you avoid using?
What happens if you write ::selection { color: red; background: blue; } but the selection doesn’t change—what’s the first thing you’d check?
Our app has a dark mode theme, and when users highlight text, the selection becomes unreadable—how would you debug and fix this?
A designer wants selected text to have a gradient background using ::selection, but it’s not working—why, and what’s your workaround?
We’re building a rich-text editor and need consistent selection styling across Chrome, Safari, and Firefox—how do you architect this without bloating CSS or causing layout shifts?
A third-party library overrides ::selection globally, breaking our UI—how would you isolate or override it without affecting other components?
We’re migrating a legacy UI from IE11 to modern browsers and need to preserve selection styling—how do you handle vendor prefixes and fallbacks at scale without introducing technical debt?
How would you design a design system token for selection styling that accommodates accessibility, theming, and cross-platform consistency across web, PWA, and embedded webviews?